#include "includes.h"
#include "app_porting.h"

bool g_second_flag;

void time2_init(void)
{
	TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
	
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);

	TIM_InternalClockConfig(TIM2);

	TIM_TimeBaseStructure.TIM_Period = 2000-1;//????72MHz  72000000/36000=2000
	TIM_TimeBaseStructure.TIM_Prescaler = 36000-1;
	TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
	TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
	TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure); 
	TIM_ARRPreloadConfig(TIM2,DISABLE);
	TIM_ClearITPendingBit(TIM2, TIM_IT_Update);
	TIM_ITConfig(TIM2, TIM_IT_Update, ENABLE );
	TIM_Cmd(TIM2,ENABLE);
}

/*******************************************************************************
* Function Name  : TIM2_IRQHandler
* Description    : This function handles TIM2 global interrupt request.
* Input          : None
* Output         : None
* Return         : None
*******************************************************************************/
void TIM2_IRQHandler(void)
{
	if(TIM_GetITStatus(TIM2, TIM_IT_Update) == SET)
	{
		TIM_ClearITPendingBit(TIM2, TIM_IT_Update);
		g_second_flag=TRUE;
		crack_timer++;
	}
}

void time5_init(void)
{
	TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
	
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM5, ENABLE);

	TIM_InternalClockConfig(TIM5);

	TIM_TimeBaseStructure.TIM_Period = 0xffff;
	TIM_TimeBaseStructure.TIM_Prescaler = 36000-1;
	TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
	TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
	TIM_TimeBaseInit(TIM5, &TIM_TimeBaseStructure); 
	TIM_ARRPreloadConfig(TIM5,DISABLE);
	TIM_Cmd(TIM5,ENABLE);
}

void time_measure_start(uint16_t *pinital)
{
	*pinital=TIM_GetCounter(TIM5);
}

uint16_t time_measure_get_ms(uint16_t inital)
{
	uint16_t cur;
	
	cur=TIM_GetCounter(TIM5);
	if(cur>=inital){
		cur-=inital;
	}else{
		cur=0xffff-inital+cur+1;
	}
	cur/=2;
	return cur;
}

void timer_init(void)
{	
	time2_init();
	time5_init();
}

